<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RX</title>
    <link href="/static/admin/css/bootstrap.min.css" rel="stylesheet">
    <link href="/static/admin/css/font-awesome.min.css" rel="stylesheet">
    <link href="/static/admin/css/plugins/bootstrap-table/bootstrap-table.min.css" rel="stylesheet">
    <link href="/static/admin/css/animate.min.css" rel="stylesheet">
    <link href="/static/admin/css/style.min.css" rel="stylesheet">
    <link href="/static/admin/css/plugins/sweetalert/sweetalert.css" rel="stylesheet">
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <!-- Panel Other -->
    <div class="ibox float-e-margins">
        <div class="ibox-title">
            <h5>管理员列表</h5>
        </div>

        <div class="ibox-content">
            <div class="form-group clearfix col-sm-4">
                <button class="btn btn-outline btn-primary" type="button" id="TableAdd" ">添加管理员</button>
                <button class="btn btn-outline btn-danger" type="button" id="TableAllDel" ">批量删除</button>
                <button class="btn btn-outline btn-info" type="button" id="TableExport" ">导出</button>
            </div>
            <div class="form-group clearfix col-sm-8 ">
                <form class="form-inline pull-right">
                    <div class="form-group">
                        <label for="searchmobile"></label>

                        <input type="text" class="form-control" name="mobile" id="searchmobile"  placeholder="登陆账号（电话）">
                    </div>
                    <div class="form-group">
                        <button  type="button" class="btn btn-info " id="search">搜索</button>
                    </div>
                </form>


            </div>
            <!--搜索框结束-->
            <div class="hr-line-dashed col-sm-12"></div>

            <div class="example-wrap">
                <div class="example">
                    <table id="cusTable" class="table table-striped table_list" data-content-type="application/x-www-form-urlencoded" >
                    </table>
                </div>
            </div>
            <!-- End Example Pagination -->
        </div>
    </div>
</div>
<!-- End Panel Other -->
</div>
<!-- 模态框（Modal） -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    <span id="actionTitle">修改</span>
                </h4>
            </div>
            <div class="modal-body">
                <form id="signupForm" method="post" class="form-horizontal" action="">
                    <input type="hidden"  id="action"/>
                    <input type="hidden" name="id" id="id" />
                    <div class="form-group">
                        <label class="col-sm-4 control-label" for="username">管理员名称</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" id="username" name="username" placeholder="请输入名称" />
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-4 control-label" for="mobile">登陆账号（电话）</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" id="mobile" name="mobile" placeholder="请输入电话" />
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-4 control-label" for="confirm_password">状态</label>
                        <div class="col-sm-8">
                            <select id="stats" name="stats" class="form-control m-b">
                                <option value="1">正常</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-9 col-sm-offset-4">
                            <button type="submit" class="btn btn-primary" >提交</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default"  data-dismiss="modal">
                    关闭
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script src="/static/admin/js/jquery.min.js"></script>
<script src="/static/admin/js/keyReset.js"></script>
<script src="/static/admin/js/bootstrap.min.js"></script>
<script src="/static/admin/js/content.min.js"></script>
<script src="/static/admin/js/plugins/bootstrap-table/bootstrap-table.min.js"></script>
<script src="/static/admin/js/plugins/bootstrap-table/bootstrap-table-mobile.min.js"></script>
<script src="/static/admin/js/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.min.js"></script>
<script src="/static/admin/js/plugins/suggest/bootstrap-suggest.min.js"></script>
<script src="/static/admin/js/plugins/layer/laydate/laydate.js"></script>
<script src="/static/admin/js/plugins/validate/jquery.validate.js"></script>
<script src="/static/admin/js/plugins/validate/messages_zh.min.js"></script>
<script src="/static/admin/js/plugins/sweetalert/sweetalert.min.js"></script>
<script src="/static/admin/js/plugins/layer/layer.min.js"></script>
<script type="text/javascript">

    function initTable() {
        //先销毁表格
        $('#cusTable').bootstrapTable('destroy');
        //初始化表格,动态从服务器加载数据
        $("#cusTable").bootstrapTable({
            method: "post",  //使用get请求到服务器获取数据
            url: "/admin/user/data", //获取数据的地址
            striped: true,  //表格显示条纹
            // toolbar : '#toolbar',             //工具栏
            pagination: true, //启动分页
            pageSize: 10,  //每页显示的记录数
            pageNumber:1, //当前第几页
            sortOrder:'asc',
            // showRefresh: true,  //是否显示刷新按钮
            // pageList: [10,20,25,30,50,100],  //记录数可选列表
            sidePagination: "server", //表示服务端请求
            uniqueId: "id",                     //每一行的唯一标识，一般为主键列
            //设置为undefined可以获取pageNumber，pageSize，searchText，sortName，sortOrder
            //设置为limit可以获取limit, offset, search, sort, order
            queryParamsType : "undefined",
            queryParams:queryParams,
            columns: [
                {
                    checkbox: true
                },
                    {
                    field: 'username',
                    title: '管理员名称',
                    sortable: true
                }, {
                    field: 'mobile',
                    title: '登陆账号（电话）'
                }, {
                    field: 'login_count',
                    title: '登陆次数',
                    sortable: true
                }, {
                    field: 'stats',
                    title: '状态',
                    sortable: true,
                    formatter:function(i,row){
                        if (i ==1){return '正常'}else {return '禁用'}
                    }
                }, {
                    field: 'last_login_time',
                    title: '上次登录时间',
                    sortable: true
                }, {
                    field:'button',
                    title: '操作',
                    events:operateEvents,
                    formatter:AddFunctionAlty,
                }
            ],
            onLoadSuccess: function(){  //加载成功时执行
                layer.msg("加载成功", {time : 2000});
            },
            onLoadError: function(){  //加载失败时执行
                layer.msg("数据加载失败");
            }
        });
    }
    function queryParams(params) {   //设置查询参数
        var param = {
            pageNumber: params.pageNumber,
            pageSize: params.pageSize,
            sort: params.sortName,
            sortOrder: params.sortOrder, //排位命令（desc，asc）
            searchText:$('#searchmobile').val()
        };
        return param;
    }
    $(document).ready(function () {
        //调用函数，初始化表格
        initTable();
        //当点击查询按钮的时候执行
        $("#search").bind("click", initTable);
    });
    window.operateEvents = {
        "click #TableEditor": function(e, value, row, index) {
            $('#myModal').modal('show');
            $('#action').val('userEdit');
            $('#id').val(row.id);
            $('#actionTitle').html('修改');
            $('#username').val(row.username);
            $('#mobile').val(row.mobile);
            $('#stats option[value='+row.stats+']').prop("selected",true);
        },
        "click #TableDelete":function (e,value,row,index) {

            layer.confirm('确认删除此管理员?', {icon: 3, title:'提示'}, function(){

                $.getJSON('./userDel', {'id' : row.id}, function(res){
                    if(res.code == 1){
                        layer.msg('删除成功', {
                                time: 1000 //2秒关闭（如果不配置，默认是3秒）
                            },function () {
                                $('#cusTable').bootstrapTable('refresh');
                            }

                        );
                    }else{
                        layer.alert('删除失败');
                    }
                });

                layer.close(index);
            })
        },
    };
    $(function () { $('#myModal').on('hide.bs.modal', function () {
            $("input").val('');
            $('#stats option[value=1]').prop("selected",true);
        })
    });
    $('#TableAdd').click(function () {

        $('#myModal').modal('show');
        $('#action').val('userAdd');
        $('#actionTitle').html('添加');
    });
    function AddFunctionAlty() {
            return[
                '<button type="button" id="TableEditor" class="btn btn-info">修改</button> &nbsp;&nbsp;',
                '<button type="button" id="TableDelete" class="btn btn-warning">删除</button>'
            ].join("")
    }
</script>
<script>
    $.validator.setDefaults( {
        submitHandler: function () {
            var action = $('#action').val();
            $.ajax({
                type: "post",//提交方式
                url: "./"+action,//提交地址
                data: $("#signupForm").serialize(),//将表单全部提交
                async: false,//设置同步或者异步,false为同步
                dataType:'json',
                success: function(data) {//成功后返回数据data，并进行操作
                    if(data.code){
                        layer.msg('操作成功', {
                                icon: 1,
                                time: 1000 //2秒关闭（如果不配置，默认是3秒）
                            },function () {
                                $('#myModal').modal('hide');
                                $('#cusTable').bootstrapTable('refresh');

                            }
                        );
                    }else {
                        layer.msg('操作失败', {
                                icon: 1,
                                time: 2000 //2秒关闭（如果不配置，默认是3秒）
                            },function () {
                                $('#myModal').modal('hide');
                                // $('#cusTable').bootstrapTable('refresh');

                            }

                        );
                    }

                }
            });
        }
    } );
    $( document ).ready( function () {
        $( "#signupForm" ).validate( {
            rules: {
                username: {
                    required: true,
                    minlength: 5
                },

                mobile: {
                    required: true,
                    digits:true,
                    maxlength:11,
                    minlength:11
                },
                agree: "required"
            },
            errorElement: "em",
            errorPlacement: function ( error, element ) {
                // Add the `help-block` class to the error element
                error.addClass( "help-block" );

                if ( element.prop( "type" ) === "checkbox" ) {
                    error.insertAfter( element.parent( "label" ) );
                } else {
                    error.insertAfter( element );
                }
            },
            highlight: function ( element, errorClass, validClass ) {
                $( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
            },
            unhighlight: function (element, errorClass, validClass) {
                $( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
            }
        } );
    } );

    $("#TableAllDel").click(function(){
        var ids = $.map($("#cusTable").bootstrapTable('getSelections'), function (row) {
            return row.id;

        });

        if(ids.length<=0){
            layer.msg('请选中最少一行！', {time: 2000});
        }else{
            layer.confirm('确认删除?', {icon: 3, title:'提示'}, function(){

                $.getJSON('./userDel', {'id' : ids}, function(res){
                    if(res.code == 001){
                        layer.msg('删除成功', {
                                icon: 1,
                                time: 1000 //2秒关闭（如果不配置，默认是3秒）
                            },function () {
                                $('#cusTable').bootstrapTable('refresh');
                            }

                        );
                    }else{
                        layer.alert('删除失败');
                    }
                });

                layer.close(index);
            })
        }

    });
    $('#TableExport').on('click', function(){
        console.log('1');
        window.location.href = '/admin/user/export';
    });
</script>
</body>
</html>